package ArraySort;

import java.util.Comparator;

public class SelectionSort {
    public static void selectionSort(Comparable[] anArray) {
        for (int index = 0; index < anArray.length - 1; index++) {
            int indexOfNextSmallest = getIndexOfSmallest(index, anArray);
            interchange(index, indexOfNextSmallest, anArray);
        }
    }//通过两个函数实现选择排序

    public static void selectionSort(Comparable[] anArray, Comparator<Comparable> b) {
        for (int index = 0; index < anArray.length - 1; index++) {
            int indexOfNextSmallest = getIndexOfSmallest(index, anArray, b);
            interchange(index, indexOfNextSmallest, anArray);
        }
    }//通过两个函数实现选择排序

    private static int getIndexOfSmallest(int startIndex, int[] a) {
        int min = a[startIndex];
        int indexOfMin = startIndex;
        for (int index = startIndex + 1; index < a.length; index++) {
            if (a[index] < min) {
                min = a[index];
                indexOfMin = index;
            }
        }
        return indexOfMin;
    }//选择函数选择数组中排序前最小数的位置
    private static int getIndexOfSmallest(int startIndex, Comparable[] a) {
        Comparable min = a[startIndex];
        int indexOfMin = startIndex;
        for (int index = startIndex + 1; index < a.length; index++) {
            if (a[index].compareTo(min)<0 ) {
                min = a[index];
                indexOfMin = index;
            }
        }
        return indexOfMin;
    }//选择函数选择数组中排序前最小数的位置

    private static int getIndexOfSmallest(int startIndex, Comparable[] a, Comparator<Comparable> b) {
        Comparable min = a[startIndex];
        int indexOfMin = startIndex;
        for (int index = startIndex + 1; index < a.length; index++) {
            if (b.compare(a[index], min) < 0) {
                min = a[index];
                indexOfMin = index;
            }
        }
        return indexOfMin;
    }//选择函数选择数组中排序前最小数的位置

    private static void interchange(int i, int j, int[] a) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }//将最小数与当前位置进行交换.3

    private static void interchange(int i, int j, Comparable[] a) {
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }//将最小数与当前位置进行交换.3


}
